from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.database import get_db
from app.api.auth import get_current_user
from app.schemas.user import UserInDB
from app.schemas.setting import (
    SystemSettingResponse, SystemSettingCreate, SystemSettingUpdate,
    UserSettingResponse, UserSettingCreate, UserSettingUpdate, SettingsBatch
)
from typing import List, Dict, Any

router = APIRouter()

# === 系统设置API ===

@router.get("/system", response_model=List[SystemSettingResponse])
def get_system_settings(
    category: str = None,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    """获取系统设置列表"""
    # 检查管理员权限
    if current_user.role != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有管理员可以访问系统设置"
        )
    
    settings = crud.setting.get_system_settings(db, category=category)
    return settings

@router.post("/system", response_model=SystemSettingResponse, status_code=status.HTTP_201_CREATED)
def create_system_setting(
    setting: SystemSettingCreate,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    """创建系统设置"""
    if current_user.role != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有管理员可以创建系统设置"
        )
    
    # 检查设置键是否已存在
    existing = crud.setting.get_system_setting_by_key(db, setting.key)
    if existing:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="设置键已存在"
        )
    
    return crud.setting.create_system_setting(db, setting)

@router.put("/system/{setting_id}", response_model=SystemSettingResponse)
def update_system_setting(
    setting_id: int,
    setting: SystemSettingUpdate,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    """更新系统设置"""
    if current_user.role != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有管理员可以更新系统设置"
        )
    
    db_setting = crud.setting.update_system_setting(db, setting_id, setting)
    if not db_setting:
        raise HTTPException(status_code=404, detail="设置不存在")
    return db_setting

@router.post("/system/batch")
def batch_update_system_settings(
    settings_batch: SettingsBatch,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    """批量更新系统设置"""
    if current_user.role != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有管理员可以更新系统设置"
        )
    
    try:
        updated_settings = []
        
        # 更新系统设置
        for key, value in settings_batch.system_settings.items():
            setting = crud.setting.update_system_setting_by_key(db, key, value)
            updated_settings.append(setting)
        
        # 更新安全设置
        for key, value in settings_batch.security_settings.items():
            setting = crud.setting.update_system_setting_by_key(db, key, value)
            updated_settings.append(setting)
        
        # 更新通知设置
        for key, value in settings_batch.notification_settings.items():
            setting = crud.setting.update_system_setting_by_key(db, key, str(value).lower())
            updated_settings.append(setting)
        
        return {"message": "设置更新成功", "updated_count": len(updated_settings)}
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新设置失败: {str(e)}"
        )

# === 用户设置API ===

@router.get("/user", response_model=List[UserSettingResponse])
def get_user_settings(
    category: str = None,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    """获取当前用户设置"""
    settings = crud.setting.get_user_settings(db, user_id=current_user.id, category=category)
    return settings

@router.post("/user", response_model=UserSettingResponse, status_code=status.HTTP_201_CREATED)
def create_user_setting(
    setting: UserSettingCreate,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    """创建用户设置"""
    return crud.setting.create_user_setting(db, user_id=current_user.id, setting=setting)

@router.put("/user/{category}")
def update_user_setting(
    category: str,
    settings: Dict[str, Any],
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    """更新用户设置"""
    try:
        setting = crud.setting.update_user_setting(db, user_id=current_user.id, category=category, settings=settings)
        return {"message": "用户设置更新成功", "setting_id": setting.id}
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新用户设置失败: {str(e)}"
        )

# === 初始化设置 ===

@router.post("/init")
def initialize_default_settings(
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    """初始化默认系统设置"""
    if current_user.role != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有管理员可以初始化系统设置"
        )
    
    try:
        crud.setting.init_default_settings(db)
        return {"message": "默认设置初始化成功"}
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"初始化设置失败: {str(e)}"
        )

# === 获取公共设置 ===

@router.get("/public")
def get_public_settings(db: Session = Depends(get_db)):
    """获取公开的系统设置（不需要认证）"""
    public_keys = [
        "system_name", "language", "theme"
    ]
    
    settings = {}
    for key in public_keys:
        value = crud.setting.get_setting_value(db, key)
        if value is not None:
            settings[key] = value
    
    return settings